import axios from "axios"
import { toast } from '~/composables/util'
import { getToken } from '~/composables/auth'
import store from "./store"
import { router } from "~/router"
import { getStorage } from '~/composables/storage'
import { useUserStore } from '~/store/login'


const service = axios.create({

  // baseURL: 'http://192.168.1.100:31600',
  // baseURL: 'http://127.0.0.1:31600',
  // baseURL: 'http://192.168.10.27:31600',
  // baseURL: 'http://61749v835s.vicp.fun',
  baseURL: 'http://43.137.0.78:31600',
  // baseURL: 'http://127.0.0.1:31600',

})
export const service1 = axios.create({
  baseURL: 'https://restapi.amap.com',
})
// 添加请求拦截器
service.interceptors.request.use(function (config) {



  const userStore = useUserStore()

  // 往header头自动添加token
  // const token = getToken()
  const token = userStore.xiaoFang_token

  if (token) {
    config.headers["token"] = token
  }

  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
service.interceptors.response.use(function (response) {

  if (response.request.responseType == "blob") {
    return response.data
  }

  // 非法token
  if (response.data.code === '0001') {

    toast(response.data.msg, "error")
    // console.log('非法token')
    // store.dispatch("clearFn")
    return router.replace("/")
  }

  if (response.data.code === '0000') {
    return response.data
  } else {
    // if(response.data.msg !== '请登录'){
    toast(response.data.msg, "error")
    // }
    return router.replace("/")
  }
  // return response.request.responseType == "blob" ? response.data : response.data.data;
}, function (error) {
  const msg = error.response.data.msg || "请求失败"

  if (msg == "非法token，请先登录！") {
    store.dispatch("clearFn").finally(() => location.reload())
  }

  // toast(msg, "error")

  return Promise.reject(error);
})

export default service